#include "kit/processor/EventProcessor.hpp"
#include "kit/message/Message.hpp"
#include "system/thread/Thread.hpp"
#include <string>

namespace KitProcessor
{
	EventProcessor::EventProcessor(KitContainer::ThreadSafeQueue<KitEvent::Event *> * iQueue):
			_eventQueue(iQueue)
	{

	}

	EventProcessor::~EventProcessor()
	{

	}

	void EventProcessor::process(SystemSocket::Connection * iConnection)
	{
		this->_connection = iConnection;
		// read from connection
		std::string aMessageString;
		do
		{
			try
			{
				aMessageString = _connection->read();
			}
			catch(SystemSocket::ReadException & aException)
			{
				// it looks like we have nothing else to read here
				delete _connection;
				SystemThread::Thread::exit();
			}

			// create new real message
			KitMessage::Message * aMessage = new KitMessage::Message(aMessageString);
			aMessage->decode();

			// create event for incoming message
			KitEvent::Event * aNewEvent = _eventCreator.createEvent(aMessage);
			// if there exist such an event
			if(aNewEvent)
				_eventQueue->push(aNewEvent);
			else
			{
				// print warning that we got unrecognized event if you need it
				// I don't :)
			}
		}
		while(aMessageString.size());
		// close connection as we don't need it anymore
		_connection->close();
		delete _connection;
	}

}
